import {
  Controller,
  Get,
  Post,
  Body,
  Req,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

import { PunchService } from './punch.service';
import { CreatePunchDto, PunchToDayFoodSummaryDto } from './dto/punch.dto';
import { ApiTags } from '@nestjs/swagger';
import { NutrientType } from '../entities';
import { UserService } from '../user/user.service';

@ApiTags('小程序/打卡日志')
@Controller('app/punch')
export class PunchController {
  constructor(
    private readonly punchService: PunchService,
    private readonly userService: UserService,
  ) {}

  /**
   * 创建打卡记录
   */
  @Post()
  createPunch(@Req() req: Request, @Body() createPunchDto: CreatePunchDto) {
    if (!req.user?.userId) {
      throw new HttpException('用户未登录', HttpStatus.UNAUTHORIZED);
    }
    return this.punchService.createPunchWithFoods(
      req.user?.userId,
      createPunchDto,
    );
  }

  /**
   * 获取打卡记录
   */
  @Get()
  findAllPunch(@Req() req: Request) {
    if (!req.user?.userId) {
      throw new HttpException('用户未登录', HttpStatus.UNAUTHORIZED);
    }
    return this.punchService.findAll(req.user?.userId);
  }

  /**
   * 获取当天状态
   */
  @Get('today-data')
  async findTodayPunch(@Req() req: Request): Promise<PunchToDayFoodSummaryDto> {
    if (!req.user?.userId) {
      throw new HttpException('用户未登录', HttpStatus.UNAUTHORIZED);
    }
    const todayData = await this.punchService.findToday(req.user?.userId);
    let totalCalories = 0;
    let totalProtein = 0;
    let totalCarbs = 0;
    let totalFat = 0;

    let resultInflammationIndex = 0;
    for (let i = 0; i < todayData.length; i++) {
      const punchFoods = todayData[i].punchFood;
      for (let j = 0; j < punchFoods.length; j++) {
        const elements = punchFoods[j].food.microElement;
        for (let k = 0; k < elements.length; k++) {
          const element = elements[k];
          resultInflammationIndex += element.amount * element.inflammationIndex;
          switch (element.type) {
            case NutrientType.CALORIES:
              totalCalories += element.amount;
              break;
            case NutrientType.PROTEIN:
              totalProtein += element.amount;
              break;
            case NutrientType.CARBS:
              totalCarbs += element.amount;
              break;
            case NutrientType.FAT:
              totalFat += element.amount;
              break;
            default:
              break;
          }
        }
      }
    }

    /**
     * 热量推荐量： 体重 kg * 30
     * 蛋白质推荐量： 体重 kg * 1.2
     * 碳水推荐量： 总热量的 50%
     * 脂肪推荐量： 总热量的 20%
     */
    const findUser = await this.userService.findCurUser(req.user?.userId);
    const weight = findUser.weight || 0;

    const calcRatio = (actual: number, target: number) => {
      if (!target) return 0; // 避免除零返回 Infinity
      return Number((actual / target).toFixed(2)) > 1
        ? 1
        : Number((actual / target).toFixed(2));
    };
    const caloriesTarget = weight * 30;
    const proteinTarget = weight * 1.2;
    const carbsTarget = totalCalories * 0.5;
    const fatTarget = totalCalories * 0.2;

    const params = {
      resultInflammationIndex,
      todayPunchCount: todayData.length,
      isHealth: resultInflammationIndex > 0,
      caloriesRatio: calcRatio(totalCalories, caloriesTarget),
      proteinRatio: calcRatio(totalProtein, proteinTarget),
      carbsRatio: calcRatio(totalCarbs, carbsTarget),
      fatRatio: calcRatio(totalFat, fatTarget),
    };

    return params;
  }
}
